﻿import com.audiopackage.GSync;
import com.audiopackage.GSound;

class com.audiopackage.GFlanger extends GSound
{
	static private var DEFAULT_SPEED: Number = .04;
	static private var DEFAULT_RANGE: Number = .001;
	
	static private var DAMP_VOLUME: Number = .6;

	private var gSync: GSync;	
	private var source: GSound;
	
	private var timer: Number;
	private var range: Number;
	private var speed: Number;
	
	private var r2: Number;
	
	function GFlanger( gSync: GSync, source: GSound, targetClip: MovieClip )
	{
		super( targetClip );
		
		( this.gSync = gSync ).addListener( this );
		( this.source = source ).addListener( this );
		
		attachSound( source.getLinkageId() );
		
		timer = 0;
		
		setSpeed( DEFAULT_SPEED );
		setRange( DEFAULT_RANGE );
	}
	
	function remove( Void ): Void
	{
		gSync.removeListener( this );
		source.removeListener( this );
	}
	
	function setRange( range: Number ): Void
	{
		if ( range > 0 && range < 1 )
		{
			this.range = range;
			r2 = range / 2;
		}
	}
	
	function getRange( Void ): Number
	{
		return range;
	}
	
	function setSpeed( speed: Number ): Void
	{
		if( speed > 0 && speed < Math.PI ) this.speed = speed;
	}
	
	function getSpeed( Void ): Number
	{
		return speed;
	}
	
	private function onSync( delay: Number ): Void
	{
		timer += speed;
	}
	
	private function onStart( gSound: GSound, delay: Number ): Void
	{
		if ( gSound == source )
		{
			var dampVolume: Number = source.getVolume() * DAMP_VOLUME;
			
			source.setVolume( dampVolume );
			setVolume( dampVolume );
			
			start( delay + Math.sin( timer ) * r2 + r2 , 1 );
		}
	}
}